package com.xinhe.web.service;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.xinhe.web.common.Result;
import com.xinhe.web.entity.AdoptedRange;
import com.xinhe.web.entity.QAdoptedRange;
import com.xinhe.web.reposity.AdoptedRangeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.inject.Provider;
import javax.persistence.EntityManager;
import java.math.BigDecimal;
import java.util.Objects;
import java.util.Optional;

@Service
public class AdoptedRangeService {
    @Autowired
    private AdoptedRangeRepository adoptedRangeRepository;
    //查询工厂
    private JPAQueryFactory queryFactory;
    @Autowired
    private Provider<EntityManager> entityManager;

    @PostConstruct
    public void init() {
        queryFactory = new JPAQueryFactory(entityManager);
    }

    public QueryResults<AdoptedRange> pageAdoptedRange(Integer minNum, Integer maxNum, BigDecimal yunChaSeed, int pageNum, int pageSize) {
        QAdoptedRange qAdoptedRange = QAdoptedRange.adoptedRange;
        BooleanBuilder builder = new BooleanBuilder();
        //OrderSpecifier<Date> sort = qAdoptedRange.createTime.desc();
        //builder.and(qShop.removed.eq(0));
        if (!Objects.isNull(minNum)) {
            builder.and(qAdoptedRange.minNum.eq(minNum));
        }
        if (!Objects.isNull(maxNum)) {
            builder.and(qAdoptedRange.maxNum.eq(maxNum));
        }
        if (!Objects.isNull(yunChaSeed)) {
            builder.and(qAdoptedRange.yunChaSeed.eq(yunChaSeed));
        }
        return queryFactory.select(
                Projections.bean(
                        AdoptedRange.class,
                        qAdoptedRange.maxNum,
                        qAdoptedRange.minNum,
                        qAdoptedRange.level,
                        qAdoptedRange.yunChaSeed,
                        qAdoptedRange.id
                )
        ).from(qAdoptedRange)
                .where(builder).offset(pageNum * pageSize).limit(pageSize).fetchResults();
    }


    public Result findById(Long adoptedRangeId) {
        Optional<AdoptedRange> byId = adoptedRangeRepository.findById(adoptedRangeId);
        return Result.ok(byId.get());
    }

    public Result delete(Long adoptedRangeId) {
        adoptedRangeRepository.deleteById(adoptedRangeId);
        return Result.ok();
    }

    public Result saveModel(Integer minNum, Integer maxNum, BigDecimal yunChaSeed, Integer level) {
        return Result.ok();
    }

}
